//
//  Preferences.m
//  Pocket Doctor alpha version
//
//  Created by Sherif, Yin, Taylor, Jacob, Anna, Mike on 11-10-25.
//  Copyright (c) 2011 __Sytjam__. All rights reserved.
//
//Class Description: 
//- Security settings (passcode, secret question and answer) - and e-mail is sent when those are modified
//- Emergency Contact (can be set up and modified here)
//- Time Settings (preference between (12hr - 24hr clock) - (long day names - short day names)
//- Reset (reset the whole application all data (wiping the application's databases))
//
//Known Bugs: none.
//
//missing features
//load refill status, ringtones, from database.
//

#import "Preferences.h"
#import "MainMenu.h"
#import "AppDelegate.h"
#import "FirstTimeLaunch.h"

int lastIndexPath = 0; //to determine which sound was checked in UITableView

@implementation Preferences

@synthesize oldPasscode, passcode, confirmNewPasscode, passcodeHint, changedPasscode, SecretQuestion, SecretAnswer, userPasscode, userSecretQuestion, userSecretAnswer, userEmailAddress, changePasscode, changeQuestionAnswer, security, timeSettings, header1, header2, back1, back2, done1, done2, emergencyContacts, doneEmergencyContact, header3, header3title, back3, emergencyContact, clockType, dayType, dateType, clockTypeLabel, dayTypeLabel, dateTypeLabel, reset, resetConfrim, refillRing, medRing, ringtoneSettings, currentMedRing, currentRefillRing, changeMedRing, changeRefillRing, ringtoneHeader, ringtoneBackButton, ringtonesList, ringtoneListHeader, backToRingTone, refillSlider, refillSettings, refillStatement;
@synthesize sounds;
@synthesize mm, ftl, aD;

/*Check if all the fields are correct for 
 changing the passcode*/
- (IBAction)donePasscode:(id)sender{
    
    [oldPasscode resignFirstResponder];
    [changedPasscode resignFirstResponder];
    [confirmNewPasscode resignFirstResponder];
    [passcode resignFirstResponder];
    [SecretQuestion resignFirstResponder];
    [SecretAnswer resignFirstResponder];
    [passcodeHint resignFirstResponder];
    [emergencyContact resignFirstResponder];
    
    
    if([oldPasscode.text isEqualToString:userPasscode.text]){
        if([changedPasscode.text length] != 4){
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Error" message:@"Passcode must be 4 digits!" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles: nil];
            [alert show];
            [alert release];
        }
        else{
            if ([changedPasscode.text hasPrefix:@"0"]) {
                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Error" message:@"Passcode can not begin with 0!" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles: nil];
                [alert show];
                [alert release];
            }
            else{
                if([changedPasscode.text isEqualToString:confirmNewPasscode.text]){
                    if(![passcodeHint.text isEqualToString:@""]){
                        NSString *dbPasscode = [[NSString alloc]initWithFormat:changedPasscode.text];
                        NSString *dbHint = [[NSString alloc]initWithFormat:passcodeHint.text];
                        //save to database

                        sqlite3_stmt * statement;
                        NSString * enforceForeignKey = @"PRAGMA foreign_keys = 1";
                        const char * query_stmt = [enforceForeignKey UTF8String];
                        if (sqlite3_prepare_v2(aD.dbPointer, query_stmt, -1, &statement, NULL) == SQLITE_OK) {
                            sqlite3_step(statement);
                            if (sqlite3_errcode(aD.dbPointer) == SQLITE_OK) {
                                sqlite3_finalize(statement);
                            }
                            else {
                                //Couldn't enforce foreign key constraint.
                            }
                        }
                        [enforceForeignKey release];
                        
                        NSString *updatePasscode = @"UPDATE Security SET passcode=?, passcode_hint=? WHERE id=1;";
                        
                        query_stmt = [updatePasscode UTF8String];
                        if (sqlite3_prepare_v2(aD.dbPointer, query_stmt, -1, &statement, NULL) == SQLITE_OK){
                            
                            sqlite3_bind_int(statement, 1, [dbPasscode intValue]);
                            sqlite3_bind_text(statement, 2, [dbHint UTF8String],-1, SQLITE_TRANSIENT);
                            
                            sqlite3_step(statement);
                            if (sqlite3_errcode(aD.dbPointer) == SQLITE_DONE){
                                sqlite3_finalize(statement);
                                
                                userPasscode.text = confirmNewPasscode.text;
                                
                                NSString *message = [[NSString alloc]initWithFormat:@"Passcode Changed.\n\nThis e-mail contains your personal passcode, Secret Question and Secret Answer. Please keep it safe. We are not responsible for you losing your passcode and secret answer.\n\nPasscode : %@\nSecret Question : %@\nSecret Answer : %@ is\n\nEnjoy using Pocket Doctor\nSytjam", userPasscode.text, userSecretQuestion.text, userSecretAnswer.text];
                                
                                NSString *to = userEmailAddress.text;
                                NSString *subject = @"Passcode updated!";
                                
                                NSString *url = [NSString stringWithFormat:@"mailto:?to=%@&subject=%@&body=%@", [to stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding], [subject stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding], [message stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]];
                                
                                [[UIApplication sharedApplication] openURL: [NSURL URLWithString: url]];
                            }
                            else {
                                // Pop up message for SQL error.
                                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Unsuccessful" message:@"Can not change Passcode." delegate:nil cancelButtonTitle:@"Done" otherButtonTitles: nil];
                                [alert show];
                                [alert release];
                            }
                        }
                        
                        [updatePasscode release];
                        
                        [dbPasscode release];
                        [dbHint release];
                    
                        oldPasscode.text = @"";
                        changedPasscode.text = @"";
                        confirmNewPasscode.text = @"";
                        passcodeHint.text = @"";
                        
                        security.hidden = false;
                        emergencyContacts.hidden = false;
                        timeSettings.hidden = false;
                        reset.hidden = false;
                        ringtoneSettings.hidden = false;
                        
                        header2.hidden = true;
                        header1.hidden = false;
                        
                        oldPasscode.hidden = true;
                        passcode.hidden = true;
                        confirmNewPasscode.hidden = true;
                        passcodeHint.hidden = true;
                        changedPasscode.hidden = true;
                        SecretQuestion.hidden = true;
                        SecretAnswer.hidden = true;
                        changePasscode.hidden = true;
                        changeQuestionAnswer.hidden = true;
                        done1.hidden = true;
                        done2.hidden = true;
                    }
                    else{
                        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Error" message:@"Please provide a hint!" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles: nil];
                        [alert show];
                        [alert release];
                    }
                }
                else{
                    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Error" message:@"Can not confirm Passcode!" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles: nil];
                    [alert show];
                    [alert release];
                }
            }
        }
    }
    else{
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Error" message:@"Incorrect Passcode!" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles: nil];
        [alert show];
        [alert release];
    }
}

/*Check if all fields are correct for changing the secret question and answer*/
- (IBAction)doneSecret:(id)sender{
    
    [oldPasscode resignFirstResponder];
    [changedPasscode resignFirstResponder];
    [confirmNewPasscode resignFirstResponder];
    [passcode resignFirstResponder];
    [SecretQuestion resignFirstResponder];
    [SecretAnswer resignFirstResponder];
    [passcodeHint resignFirstResponder];
    [emergencyContact resignFirstResponder];
    
    if([passcode.text isEqualToString:userPasscode.text]){
        NSString *dbQuestion = [[NSString alloc]initWithFormat:SecretQuestion.text];
        NSString *dbAnswer = [[NSString alloc]initWithFormat:[SecretAnswer.text lowercaseString]];
        userSecretAnswer.text = dbAnswer;
        userSecretQuestion.text = dbQuestion;
        
        if(([dbQuestion isEqualToString:@""]) || ([dbAnswer isEqualToString:@""])){
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Error" message:@"Secret Question or Answer can not be empty!" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles: nil];
            [alert show];
            [alert release];
        }
        else{
        
            //Start save to database
            
            sqlite3_stmt * statement;
            NSString * enforceForeignKey = @"PRAGMA foreign_keys = 1";
            const char * query_stmt = [enforceForeignKey UTF8String];
            if (sqlite3_prepare_v2(aD.dbPointer, query_stmt, -1, &statement, NULL) == SQLITE_OK) {
                sqlite3_step(statement);
                if (sqlite3_errcode(aD.dbPointer) == SQLITE_OK) {
                    sqlite3_finalize(statement);
                }
                else {
                    //Couldn't enforce foreign key constraint.
                }
            }
            [enforceForeignKey release];
            
            NSString *updateQA = @"UPDATE Security SET secret_question=?, secret_answer=? WHERE id=1;";
            
            query_stmt = [updateQA UTF8String];
            if (sqlite3_prepare_v2(aD.dbPointer, query_stmt, -1, &statement, NULL) == SQLITE_OK){
                
                sqlite3_bind_text(statement, 1, [dbQuestion UTF8String],-1, SQLITE_TRANSIENT);
                sqlite3_bind_text(statement, 2, [dbAnswer UTF8String],-1, SQLITE_TRANSIENT);
                
                sqlite3_step(statement);
                if (sqlite3_errcode(aD.dbPointer) == SQLITE_DONE){
                    sqlite3_finalize(statement);

                    NSString *message = [[NSString alloc]initWithFormat:@"Secret Question and Answer Changed.\n\nThis e-mail contains your personal passcode, Secret Question and Secret Answer. Please keep it safe. We are not responsible for you losing your passcode and secret answer.\n\nPasscode : %@\nSecret Question : %@\nSecret Answer : %@ is\n\nEnjoy using Pocket Doctor\nSytjam", userPasscode.text, dbQuestion, dbAnswer];
                     
                     NSString *to = userEmailAddress.text;
                     NSString *subject = @"Passcode updated!";
                     
                     NSString *url = [NSString stringWithFormat:@"mailto:?to=%@&subject=%@&body=%@", [to stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding], [subject stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding], [message stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]];
                    
                    [[UIApplication sharedApplication] openURL: [NSURL URLWithString: url]];
                }
                else {
                    // Pop up message for SQL error.
                    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Unsuccessful" message:@"Can not change Secret Question and Answer" delegate:nil cancelButtonTitle:@"Done" otherButtonTitles: nil];
                    [alert show];
                    [alert release];
                }
            }
            [updateQA release];
            
            //Done saving to database
            [dbQuestion release];
            [dbAnswer release];
            
            passcode.text = @"";
            SecretQuestion.text = @"";
            SecretAnswer.text = @"";
            
            security.hidden = false;
            emergencyContacts.hidden = false;
            timeSettings.hidden = false;
            reset.hidden = false;
            ringtoneSettings.hidden = false;

            header2.hidden = true;
            header1.hidden = false;
            
            oldPasscode.hidden = true;
            passcode.hidden = true;
            confirmNewPasscode.hidden = true;
            changedPasscode.hidden = true;
            SecretQuestion.hidden = true;
            SecretAnswer.hidden = true;
            changePasscode.hidden = true;
            changeQuestionAnswer.hidden = true;
            done1.hidden = true;
            done2.hidden = true;
        }
    }
    else{
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Error" message:@"Incorrect Passcode!" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles: nil];
        [alert show];
        [alert release];
    }
}

- (IBAction)RingtoneSetting:(id)sender{
    security.hidden = true;
    emergencyContacts.hidden = true;
    timeSettings.hidden = true;
    reset.hidden = true;
    ringtoneSettings.hidden = true;
    refillSettings.hidden = true;
    
    ringtoneHeader.hidden = false;
    
    medRing.hidden = NO;
    refillRing.hidden = NO;
    currentMedRing.hidden = NO;
    currentRefillRing.hidden = NO;
    changeMedRing.hidden = NO;
    changeRefillRing.hidden = NO;
}

- (IBAction)ChangeMedicineRingtone:(id)sender{
    
    medRing.hidden = true;
    refillRing.hidden = true;
    currentMedRing.hidden = true;
    currentRefillRing.hidden = true;
    changeMedRing.hidden = true;
    changeRefillRing.hidden = true;
    
    ringtonesList.hidden = false;
    ringtoneListHeader.hidden = false;
}

- (IBAction)ChangeRefillRingtone:(id)sender{
    
    medRing.hidden = true;
    refillRing.hidden = true;
    currentMedRing.hidden = true;
    currentRefillRing.hidden = true;
    changeMedRing.hidden = true;
    changeRefillRing.hidden = true;
    
    ringtonesList.hidden = false;
    ringtoneListHeader.hidden = false;
}

- (IBAction)doneChangingRingtone:(id)sender{
    
    medRing.hidden = false;
    refillRing.hidden = false;
    currentMedRing.hidden = false;
    currentRefillRing.hidden = false;
    changeMedRing.hidden = false;
    changeRefillRing.hidden = false;
    
    ringtonesList.hidden = true;
    ringtoneListHeader.hidden = true;
}

- (IBAction)RefillSettings:(id)sender{

    security.hidden = true;
    emergencyContacts.hidden = true;
    timeSettings.hidden = true;
    reset.hidden = true;
    ringtoneSettings.hidden = true;
    refillSettings.hidden = true;
    
    header3.hidden = false;
    header3title.title = @"Refill Settings";
    
    refillStatement.hidden = false;
    refillSlider.hidden = false;
    
    NSString *statement = [[NSString alloc]initWithFormat:@"Alert triggers when you have %i%% left", (int) refillSlider.value];
    
    refillStatement.text = statement;
    
    [statement release];
}

- (IBAction)RefillStatement:(id)sender{
    
    NSString *statement = [[NSString alloc]initWithFormat:@"Alert triggers when you have %i%% left", (int) refillSlider.value];
    
    refillStatement.text = statement;
    
    [statement release];
}

/*Go back to main menu*/
- (IBAction)Header1Back:(id)sender{
    //Go to main menu
    
    [self dismissModalViewControllerAnimated:YES];
    
    /*MainMenu *mmObject = [[MainMenu alloc]initWithNibName:@"MainMenu" bundle:nil];
    self.mm = mmObject;
    [mmObject release];
     
    mm.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    [self presentModalViewController:mm animated:YES];*/
}

/*back to settings*/
- (IBAction)Header2Back:(id)sender{
    [oldPasscode resignFirstResponder];
    [changedPasscode resignFirstResponder];
    [confirmNewPasscode resignFirstResponder];
    [passcode resignFirstResponder];
    [SecretQuestion resignFirstResponder];
    [SecretAnswer resignFirstResponder];
    [emergencyContact resignFirstResponder];
    
    //    CREATE TABLE Settings (id integer primary key unique, emergency_contact integer, clock_setting integer, date_setting integer, day_setting integer);"
    
    if (clockTypeLabel.hidden == false){
        int clock_type = clockType.selectedSegmentIndex;
        int date_type = dateType.selectedSegmentIndex;
        int day_type = dayType.selectedSegmentIndex;
        
        //save into database.
        sqlite3_stmt * statement;
        NSString * enforceForeignKey = @"PRAGMA foreign_keys = 1";
        const char * query_stmt = [enforceForeignKey UTF8String];
        if (sqlite3_prepare_v2(aD.dbPointer, query_stmt, -1, &statement, NULL) == SQLITE_OK) {
            sqlite3_step(statement);
            if (sqlite3_errcode(aD.dbPointer) == SQLITE_OK) {
                sqlite3_finalize(statement);
            }
            else {
                //Couldn't enforce foreign key constraint.
            }
        }
        [enforceForeignKey release];
        
        NSString *updateTime = @"UPDATE Settings SET clock_setting=?, date_setting=?, day_setting=? WHERE id=1;";
        
        query_stmt = [updateTime UTF8String];
        if (sqlite3_prepare_v2(aD.dbPointer, query_stmt, -1, &statement, NULL) == SQLITE_OK){
            
            sqlite3_bind_int(statement, 1, clock_type);
            sqlite3_bind_int(statement, 2, date_type);
            sqlite3_bind_int(statement, 3, day_type);
            
            sqlite3_step(statement);
            if (sqlite3_errcode(aD.dbPointer) == SQLITE_DONE){
                sqlite3_finalize(statement);
            }
            else {
                // Pop up message for SQL error.
                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Unsuccessful" message:@"Can not change settings" delegate:nil cancelButtonTitle:@"Done" otherButtonTitles: nil];
                [alert show];
                [alert release];
            }
        }
        [updateTime release];
    }

    
    passcode.text = @"";
    emergencyContact.text = @"";
    SecretQuestion.text = @"";
    SecretAnswer.text = @"";
    oldPasscode.text = @"";
    changedPasscode.text = @"";
    confirmNewPasscode.text = @"";
    passcodeHint.text = @"";
    
    security.hidden = false;
    emergencyContacts.hidden = false;
    timeSettings.hidden = false;
    reset.hidden = false;
    ringtoneSettings.hidden = false;
    refillSettings.hidden = false;
    
    header3.hidden = true;
    header2.hidden = true;
    header1.hidden = false;
    header3title.title = @"Emergency Contacts";
    ringtoneHeader.hidden = true;
    
    oldPasscode.hidden = true;
    passcode.hidden = true;
    confirmNewPasscode.hidden = true;
    passcodeHint.hidden = true;
    changedPasscode.hidden = true;
    SecretQuestion.hidden = true;
    SecretAnswer.hidden = true;
    changePasscode.hidden = true;
    changedPasscode.hidden = true;
    changeQuestionAnswer.hidden = true;
    done1.hidden = true;
    done2.hidden = true;
    doneEmergencyContact.hidden = true;
    emergencyContact.hidden = true;
    
    clockType.hidden = true;
    dayType.hidden = true;
    dateType.hidden = true;
    clockTypeLabel.hidden = true;
    dayTypeLabel.hidden = true;
    dateTypeLabel.hidden = true;
    
    resetConfrim.hidden = true;
    
    medRing.hidden = true;
    refillRing.hidden = true;
    currentMedRing.hidden = true;
    currentRefillRing.hidden = true;
    changeMedRing.hidden = true;
    changeRefillRing.hidden = true;
    
    refillSlider.hidden = true;
    refillStatement.hidden = true;
}

//going to emergency contact settings
- (IBAction)ChooseEmergencyContacts{
    
    emergencyContacts.hidden = true;
    timeSettings.hidden = true;
    security.hidden = true;
    reset.hidden = true;
    ringtoneSettings.hidden = true;
    refillSettings.hidden = true;
    
    header3.hidden = false;
    header1.hidden = true;
    passcode.hidden = false;
    doneEmergencyContact.hidden = false;
    emergencyContact.hidden = false;
}

//finishing emergency button
- (IBAction)DoneChangeEmergency:(id)sender{
        
    if (![emergencyContact.text isEqualToString:@""]){
        NSString *number = emergencyContact.text;
        
        //save into database.
        sqlite3_stmt * statement;
        NSString * enforceForeignKey = @"PRAGMA foreign_keys = 1";
        const char * query_stmt = [enforceForeignKey UTF8String];
        if (sqlite3_prepare_v2(aD.dbPointer, query_stmt, -1, &statement, NULL) == SQLITE_OK) {
            sqlite3_step(statement);
            if (sqlite3_errcode(aD.dbPointer) == SQLITE_OK) {
                sqlite3_finalize(statement);
            }
            else {
                //Couldn't enforce foreign key constraint.
            }
        }
        [enforceForeignKey release];
        
        NSString *updateEmergency = @"UPDATE Settings SET emergency_contact=? WHERE id=1;";
        
        query_stmt = [updateEmergency UTF8String];
        if (sqlite3_prepare_v2(aD.dbPointer, query_stmt, -1, &statement, NULL) == SQLITE_OK){
            
            sqlite3_bind_text(statement, 1, [number UTF8String],-1, SQLITE_TRANSIENT);
            
            sqlite3_step(statement);
            if (sqlite3_errcode(aD.dbPointer) == SQLITE_DONE){
                sqlite3_finalize(statement);
                
                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Success" message:@"Emergency Number Updated Successfully" delegate:nil cancelButtonTitle:@"Done" otherButtonTitles: nil];
                [alert show];
                [alert release];
            }
            else {
                // Pop up message for SQL error.
                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Unsuccessful" message:@"Can not Add Entry" delegate:nil cancelButtonTitle:@"Done" otherButtonTitles: nil];
                [alert show];
                [alert release];
            }
        }
        [updateEmergency release];
    
        //end saving
        
        [oldPasscode resignFirstResponder];
        [changedPasscode resignFirstResponder];
        [confirmNewPasscode resignFirstResponder];
        [passcode resignFirstResponder];
        [SecretQuestion resignFirstResponder];
        [SecretAnswer resignFirstResponder];
        [emergencyContact resignFirstResponder];
        
        passcode.text = @"";
        SecretQuestion.text = @"";
        SecretAnswer.text = @"";
        oldPasscode.text = @"";
        changedPasscode.text = @"";
        confirmNewPasscode.text = @"";
        passcodeHint.text = @"";
        
        security.hidden = false;
        emergencyContacts.hidden = false;
        timeSettings.hidden = false;
        reset.hidden = false;
        ringtoneSettings.hidden = false;
        refillSettings.hidden = false;
        
        
        header3.hidden = true;
        header2.hidden = true;
        header1.hidden = false;
        
        oldPasscode.hidden = true;
        passcode.hidden = true;
        confirmNewPasscode.hidden = true;
        passcodeHint.hidden = true;
        changedPasscode.hidden = true;
        SecretQuestion.hidden = true;
        SecretAnswer.hidden = true;
        changePasscode.hidden = true;
        changedPasscode.hidden = true;
        changeQuestionAnswer.hidden = true;
        done1.hidden = true;
        done2.hidden = true;
        doneEmergencyContact.hidden = true;
        emergencyContact.hidden = true;
        refillSlider.hidden = true;
        refillStatement.hidden = true;
        
        emergencyContact.placeholder = emergencyContact.text;
        emergencyContact.text = @"";
    }
}

//check passcode if trying to edit emergency button
- (IBAction)checkPasscodeEmergency:(id)sender{
    if (![passcode.text isEqualToString:userPasscode.text]) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Error" message:@"Passcode incorrect" delegate:self cancelButtonTitle:@"Ok!" otherButtonTitles:nil];
        [alert show];
        [alert release];
        [passcode becomeFirstResponder];
        passcode.text = @"";
    }
}

//Going to time settings
- (IBAction)ChooseTimeSettings:(id)sender{
    header1.hidden = true;
    header3.hidden = false;
    header3title.title = @"Time Settings";
    
    security.hidden = true;
    emergencyContacts.hidden = true;
    timeSettings.hidden = true;
    reset.hidden = true;
    ringtoneSettings.hidden = true;
    refillSettings.hidden = true;
    
    clockType.hidden = false;
    dayType.hidden = false;
    dateType.hidden = false;
    clockTypeLabel.hidden = false;
    dayTypeLabel.hidden = false;
    dateTypeLabel.hidden = false;
}

/*Security will give you the choice of changing
 passcode or secret question and answer*/
- (IBAction)Security:(id)sender{
    header1.hidden = true;
    header2.hidden = false;
    
    security.hidden = true;
    emergencyContacts.hidden = true;
    timeSettings.hidden = true;
    reset.hidden = true;
    ringtoneSettings.hidden = true;
    refillSettings.hidden = true;

    changePasscode.hidden = false;
    changeQuestionAnswer.hidden = false;
}

/*change passcode will display the 
 related fields and hide others*/
- (IBAction)ChangePasscode:(id)sender{
    changePasscode.hidden = true;
    changeQuestionAnswer.hidden = true;
    
    changedPasscode.hidden = false;
    oldPasscode.hidden = false;
    confirmNewPasscode.hidden = false;
    passcodeHint.hidden = false;
    done1.hidden = false;
}

/*Change secret question and answer
 will display the related fields and hide all others*/
- (IBAction)ChangeSecret:(id)sender{
    changePasscode.hidden = true;
    changeQuestionAnswer.hidden = true;

    passcode.hidden = false;
    SecretAnswer.hidden = false;
    SecretQuestion.hidden = false;
    done2.hidden = false;
}

//going to reset option
- (IBAction)ResetButton:(id)sender{
    
    header3title.title = @"Reset";
    header1.hidden = true;
    header3.hidden = false;
    
    security.hidden = true;
    emergencyContacts.hidden = true;
    timeSettings.hidden = true;
    reset.hidden = true;
    ringtoneSettings.hidden = true;
    refillSettings.hidden = true;
    
    passcode.hidden = false;
    resetConfrim.hidden = false;
}

//reset confirmation
- (IBAction)ResetDatabases:(id)sender{
    UIAlertView *alert;
    [passcode resignFirstResponder];
    
    if ([userPasscode.text isEqualToString:passcode.text]) {
        alert = [[UIAlertView alloc]initWithTitle:@"Reset Application" message:@"All your data will be lost. This action cannot be undone." delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Confirm", nil];
    }
    else{
        passcode.text = @"";
        alert = [[UIAlertView alloc]initWithTitle:@"Incorrect Passcode" message:@"Passcode doesn't match User Passcode" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
    }
    
    [alert show];
    [alert release];
}

//resetting the application - remove all databases and all related files.
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1) {
        
        NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];        
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSString * databasePath = [documentsDirectory stringByAppendingPathComponent:@"PocketDoctor.db"];

        sqlite3_close(aD.dbPointer);
        
        // Delete current database
        [fileManager removeItemAtPath:databasePath error:NULL];
        // Remove all of the local notifications
        [[UIApplication sharedApplication] cancelAllLocalNotifications];
        
        // Build new database
        [aD initDB];
		[aD createDB];
		
        // Initiate the first time launch
		FirstTimeLaunch *ftlObject = [[FirstTimeLaunch alloc]initWithNibName:@"FirstTimeLaunch" bundle:nil];
		self.ftl = ftlObject;
		
		[ftlObject release];
		
		[self.view addSubview:ftl.view];
                
        passcode.text = @"";
    }
}

//Support Functions
/*Tapping the background gets rid of the keyboard*/
- (IBAction)TapBackground:(id)sender{
    [oldPasscode resignFirstResponder];
    [changedPasscode resignFirstResponder];
    [confirmNewPasscode resignFirstResponder];
    [passcodeHint resignFirstResponder];
    [passcode resignFirstResponder];
    [SecretQuestion resignFirstResponder];
    [SecretAnswer resignFirstResponder];
    [emergencyContact resignFirstResponder];
}

/*Tapping done on the keyboard gets rid of the keyboard*/
- (IBAction)DoneKeyboard:(id)sender{
    [sender resignFirstResponder];
}

/*Animate screen upwards to prevent keyboard 
 overlaying the textfields*/
- (IBAction)textFieldDidBeginEditing:(UITextField *)textField
{
    [self animateTextField: textField up: YES];
}


- (IBAction)textFieldDidEndEditing:(UITextField *)textField
{
    [self animateTextField: textField up: NO];
}

- (void) animateTextField: (UITextField *) textField up: (BOOL) up
{
    const int movementDistance = 80; // tweak as needed
    const float movementDuration = 0.3f; // tweak as needed
    
    int movement = (up ? -movementDistance : movementDistance);
    
    [UIView beginAnimations: @"anim" context: nil];
    [UIView setAnimationBeginsFromCurrentState: YES];
    [UIView setAnimationDuration: movementDuration];
    self.view.frame = CGRectOffset(self.view.frame, 0, movement);
    [UIView commitAnimations];
}
//end of animation


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

//Sound Table View
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *SimpleTableIdentifier = @"SimpleTableIdentifier";
    UITableViewCell *cell = [tableView
                             dequeueReusableCellWithIdentifier:SimpleTableIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SimpleTableIdentifier] autorelease];
    }
    
    int rowIndex = [indexPath row];
    
    if (rowIndex == lastIndexPath) 
    {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    } 
    else 
    {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    
    cell.textLabel.text = [[NSString alloc]initWithFormat:@"%@", [sounds objectAtIndex:rowIndex]];
    
    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.sounds count];
}

/*An action sheet is displayed when a row is selected in the time table*/
- (void) tableView:(UITableView *) tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    int rowIndex = [indexPath row];
    
    CFBundleRef mainBundle = CFBundleGetMainBundle();
    CFURLRef soundFileURLRef;
    soundFileURLRef = CFBundleCopyResourceURL(mainBundle, (CFStringRef) [sounds objectAtIndex:rowIndex], CFSTR ("caf"), NULL);
    UInt32 soundID;

    AudioServicesCreateSystemSoundID(soundFileURLRef, &soundID);
    AudioServicesPlaySystemSound(soundID);
    
    lastIndexPath = rowIndex;
    
    [ringtonesList deselectRowAtIndexPath:indexPath animated:NO];
    [ringtonesList reloadData];
}


#pragma mark - View lifecycle

/*Load user passcode*/
- (void)viewDidLoad
{
    //Load Database
    aD = [[UIApplication sharedApplication] delegate];
    
    sqlite3_stmt * statement;
    NSString * enforceForeignKey = @"PRAGMA foreign_keys = 1";
    const char * query_stmt = [enforceForeignKey UTF8String];
    
    NSString *loadSecurity= [[NSString alloc]initWithFormat:@"SELECT passcode, secret_question, secret_answer FROM security;"];
    
    query_stmt = [loadSecurity UTF8String];
    if (sqlite3_prepare_v2(aD.dbPointer, query_stmt, -1, &statement, NULL) == SQLITE_OK){
        
        if (sqlite3_step(statement) == SQLITE_ROW){
            NSString *userPasscodeObject = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 0)];
         
            userPasscode.text = userPasscodeObject;
            userSecretQuestion.text = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 1)];
            userSecretAnswer.text = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 2)];
        }
    }
    
    NSString *loadSettings= @"SELECT emergency_contact, clock_setting, date_setting, day_setting, email_address FROM Settings;";
    query_stmt = [loadSettings UTF8String];
    
    if (sqlite3_prepare_v2(aD.dbPointer, query_stmt, -1, &statement, NULL) == SQLITE_OK){
        
        if (sqlite3_step(statement) == SQLITE_ROW){
           
            NSString *emergencyNumberObject;
            const char * storedNumber = (char *)sqlite3_column_text(statement, 0);
            if(storedNumber != nil){
                emergencyNumberObject = [NSString stringWithUTF8String:storedNumber];
            }
            else
            {
                emergencyNumberObject = @"Not Setup Yet";
            }

            int clockSettingObject = sqlite3_column_int(statement, 1);
            int dateSettingObject = sqlite3_column_int(statement, 2);
            int daySettingObject = sqlite3_column_int(statement, 3);
            
            emergencyContact.placeholder = emergencyNumberObject;
            userEmailAddress.text = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 4)];
            
            clockType.selectedSegmentIndex = clockSettingObject;
            dayType.selectedSegmentIndex = daySettingObject;
            dateType.selectedSegmentIndex = dateSettingObject;

        }
    }

    [loadSettings release];
    [loadSecurity release];
    
    clockType.tintColor = header3.tintColor;
    dateType.tintColor = header3.tintColor;
    dayType.tintColor = header3.tintColor;
    
    NSArray *soundsObject = [[NSArray alloc]initWithObjects:@"pling", @"default", @"tot tot", nil];
    self.sounds = soundsObject;
    [soundsObject release];
    
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

/*release all outlets*/
- (void) dealloc{
    
    [mm release];
    [aD release];
    [ftl release];
    
    [oldPasscode release];
    [changedPasscode release];
    [confirmNewPasscode release];
    [passcodeHint release];
    [passcode release];
    [SecretQuestion release];
    [SecretAnswer release];
    [emergencyContact release];
    [userPasscode release];
    [userSecretQuestion release];
    [userSecretAnswer release];
    [changePasscode release];
    [changeQuestionAnswer release];
    [security release];
    [emergencyContacts release];
    [timeSettings release];
    [doneEmergencyContact release];
    [header1 release];
    [header2 release];
    [header3 release];
    [header3title release];
    [back1 release];
    [back2 release];
    [back3 release];
    [done1 release];
    [done2 release];
    [clockType release];
    [dayType release];
    [dateType release];
    [clockTypeLabel release];
    [dayTypeLabel release];
    [dateTypeLabel release];
    [reset release];
    [resetConfrim release];
    
    
    [super dealloc];
}

@end
